﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Tradukisto.Engine.Utilities
{
    internal class EnumUtilities
    {
        /// <summary>
        /// Returns true if a type is an enumerable 
        /// </summary>
        /// <typeparam name="T">Generic type argument</typeparam>
        /// <returns></returns>
        public static bool IsEnum<T>()
        {
            return GetUnderlyingType<T>().IsEnum;
        }

        /// <summary>
        /// Returns the underlying type of the specified nullable type
        /// </summary>
        /// <typeparam name="T">The underlying value type</typeparam>
        public static Type GetUnderlyingType<T>()
        {
            Type realModelType = typeof(T);
            Type underlyingType = Nullable.GetUnderlyingType(realModelType);

            if (underlyingType != null)
                return underlyingType;

            return realModelType;
        }

        public static Dictionary<TEnum, string> GetEnumValues<TEnum>(Type resourceType)
        {
            bool isEnum = IsEnum<TEnum>();

            if (!isEnum)
                throw new ArgumentException("T must be an enumerated type");

            // if no resource specified, tries to find [LocalizationEnum]
            if (resourceType == null)
                resourceType = GetResourceType<TEnum>();

            var enumDictionary = new Dictionary<TEnum, string>();

            Type enumType = GetUnderlyingType<TEnum>();
            IEnumerable<TEnum> values = Enum.GetValues(enumType).Cast<TEnum>();

            foreach (var value in values)
            {
                string localizedString = GetLocalizedString<TEnum>(resourceType, value);
                enumDictionary.Add(value, localizedString);
            }

            return enumDictionary;
        }
    }
}
